import json

from django.http import JsonResponse
from django.shortcuts import render
from .models import MXgoods,MXminpicture
from common.goodlist import goodsindex,goodslist
from django_redis import get_redis_connection
from common.get_cart_data import get_cart_data,get_all_num,save_cart_data

# Create your views here.
def goodsdes(request,id):
    goodsindexs = goodsindex()
    goodslists = goodslist()
    goodsdes = MXgoods.objects.get(id=id)
    goodpictures = MXminpicture.objects.filter(gid=id)
    cartdata = get_cart_data(request)
    all = get_all_num(request)

    context = {
        'id':id,
        'goodsindexs':list(goodsindexs),
        'goodslists':goodslists,
        'goodsdes':goodsdes,
        'goodpictures':goodpictures,
        'cartdata':cartdata,
        'all':all
    }
    return render(request,'goods_des.html',context)


def cartdata(request):
    gid = request.POST.get('gid')
    num = request.POST.get('num',"1")
    selected = request.POST.get('selected', '1')
    # print(gid)
    # print(num)

    cart_data = get_cart_data(request)

    if not cart_data:
        cart_data = {gid:{'num':num,'selected': selected}}
    else:
        cart_data[gid] = {'num':num,'selected': selected}
        for gid in list(cart_data.keys()):
            if cart_data[gid]['num'] == '0':
                del cart_data[gid]

    res = save_cart_data(request,cart_data)
    return res

